// 创建任务 
const gulp = require('gulp'),
    htmlmin = require('gulp-htmlmin'),
    sass = require('gulp-sass'),
    cleanCss = require('gulp-clean-css'),
    del = require('del'),
    babel = require('gulp-babel'),
    uglify = require('gulp-uglify'),
    connect = require('gulp-connect')

const paths = {
    htmlPath: {
        src: './src/**/*.html',
        dest: './dist'
    },
    cssPath: {
        src: './src/sass/*.scss',
        dest: './dist/css'
    },
    jsPath: {
        src: './src/js/*.js',
        dest: './dist/js'
    }
}
const { htmlPath, cssPath, jsPath } = paths
// 删除 dist    
const delDist = () => del('./dist')
// 每一个任务都是函数
const html = () => {
    return gulp.src(htmlPath.src)
        .pipe(htmlmin({
            removeComments: true, // 清除HTML注释
            collapseWhitespace: true, // 压缩HTML
            collapseBooleanAttributes: true, // 省略布尔属性的值 <input checked="true"/> ==> <input checked />
            removeEmptyAttributes: true, // 删除所有空格作属性值 <input id="" /> ==> <input />
            removeScriptTypeAttributes: false, // 删除<script>的type="text/javascript"
            removeStyleLinkTypeAttributes: false, // 删除<style>和<link>的type="text/css"
            minifyJS: true, // 压缩页面JS
            minifyCSS: true // 压缩页面CSS 
        }))
        .pipe(gulp.dest(htmlPath.dest))
        .pipe(connect.reload())
}

const css = () => {
    return gulp.src(cssPath.src)
        .pipe(sass())
        .pipe(cleanCss())
        .pipe(gulp.dest(cssPath.dest))
        .pipe(connect.reload())
}

// js任务
const js = () => {
    return gulp.src(jsPath.src)
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(uglify())
        .pipe(gulp.dest(jsPath.dest))
        .pipe(connect.reload())
}

// 复制 lib 文件夹
const lib = () => gulp.src('./src/lib/**/*.*').pipe(gulp.dest('./dist/lib'))
// 复制  img / .ico
const img = () => gulp.src('./src/images/*.*').pipe(gulp.dest('./dist/images'))
const ico = () => gulp.src('./src/*.ico').pipe(gulp.dest('./dist'))

// 服务器任务
const server = () => {
    connect.server({
        livereload: true,
        port: 2222,
        root: 'dist'
    })
}
// 监听任务
const watch = () => {
    gulp.watch(htmlPath.src,html)
    gulp.watch(cssPath.src,css)
    gulp.watch(jsPath.src,js)
}

// series 同步执行任务 
// parallel 异步执行任务 
module.exports.default = gulp.series(delDist, gulp.parallel(html, css, js, lib, img, ico,server,watch))